function elementProxy(prop) {
    var proxy_obj = Element.prototype[prop];
    Element.prototype[prop] = function (elem) {
        var tag = elem?.tagName?.toLowerCase();
        if (tag == "script") {
            var url = elem.src;
            if (url.indexOf('http') == 0 && url.indexOf(location.origin) == -1) return;
        };
        return proxy_obj.apply(this, arguments);
    };
}

function removeAd(a) {
    if (a == null) return;
    var p = a.parentNode;
    a.remove();
    if (p?.children?.length > 0) return;
    removeAd(p);
}
var removeAdCount = 0;
function getAds() {
    if (removeAdCount > 3) return;
    removeAdCount++;
    var list = document.querySelectorAll("a");
    for (var i = list.length - 1; i >= 0; i--) {
        var a = list[i];
        var url = a.getAttribute("href");
        if (!url) continue;
        if (url.indexOf('ad') > 0) removeAd(a);
        if (url.indexOf('http') == 0 && url.indexOf(location.origin) == -1) removeAd(a);
    }
    //可能会误伤
    list = document.querySelectorAll("div,img");
    for (var i = list.length - 1; i >= 0; i--) {
        var a = list[i];
        if (a.style.position == "fixed") {
            notifyApp(a.outerHTML);
            removeAd(a);
            continue;
        }
        if (window.getComputedStyle(a).position == "fixed") {
            notifyApp(a.outerHTML);
            removeAd(a);
            continue;
        }
    }
    setTimeout(getAds, 1000);
}
function notifyApp(a) {
    window.flutter_inappwebview.callHandler("sendToApp", { type: "text", message: a });
}
function initAdBlock() {
    //if (location.host.indexOf('baidu.com') ==-1) {}}
    elementProxy('appendChild');
    elementProxy('insertBefore');
    elementProxy('insertAfter');
    var oldOpen = window.open;
    window.open = function (a) {
        if (a.indexOf('http') == -1) return oldOpen.apply(this, arguments);
        if (a.indexOf(location.host) >= 0) return oldOpen.apply(this, arguments);
    }
    document.addEventListener('DOMContentLoaded', function () {
        getAds();
        window.flutter_inappwebview.callHandler("sendToApp", { type: "background", message: window.getComputedStyle(document.body).backgroundColor });
    });
    setTimeout(function () {
        if (removeAdCount == 0) getAds();
    }, 2000);
}
initAdBlock();